package com.ossjk.oa.advisory.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.ExcelUtiles;
import com.ossjk.oa.advisory.entity.Customer;
import com.ossjk.oa.advisory.entity.Customerfw;
import com.ossjk.oa.advisory.entity.Discipline;
import com.ossjk.oa.advisory.entity.School;
import com.ossjk.oa.advisory.mapper.CustomerMapper;
import com.ossjk.oa.advisory.mapper.CustomerfwMapper;
import com.ossjk.oa.advisory.mapper.DisciplineMapper;
import com.ossjk.oa.advisory.mapper.SchoolMapper;
import com.ossjk.oa.advisory.service.ICustomerService;
import com.ossjk.oa.advisory.service.ISchoolService;
import com.ossjk.oa.advisory.vo.Customer51JobVo;
import com.ossjk.oa.advisory.vo.CustomerResumeVo;
import com.ossjk.oa.advisory.vo.CustomerVo;
import com.ossjk.oa.system.entity.EmployeePost;
import com.ossjk.oa.system.mapper.EmployeePostMapper;

/**
 * <p>
 * 客户信息表 服务实现类
 * </p>
 *
 * @author chair
 * @since 2019-02-15
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {
	@Autowired
	private EmployeePostMapper employeePostMapper;

	@Autowired
	private CustomerMapper customerMapper;

	@Autowired
	private CustomerfwMapper customerfwMapper;

	@Autowired
	private SchoolMapper schoolMapper;

	@Override
	public Page selectVoPage(Page page, Wrapper wrapper, String userid, List<String> postids) {
		// TODO Auto-generated method stub
		SqlHelper.fillWrapper(page, wrapper);
		// 查询所有子岗位
		// String postid = baseMapper.selectPostId(userid);
		// String[] postids = postid.split(",");

		Wrapper wrapper2 = Condition.create().in("pid", postids);
		// 查询所有岗位员工
		List<EmployeePost> employeePosts = employeePostMapper.selectList(wrapper2);
		List list = new ArrayList();
		for (EmployeePost object : employeePosts) {
			list.add(object.getEid());
		}
		// 查询用户是否市场总监，市场总监可以查看没有跟进人的信息
		EmployeePost entity = new EmployeePost();
		entity.setEid(userid);
		entity = employeePostMapper.selectOne(entity);
		if (!CommonUtil.isEquals("f431d1109d6b4accbadca9d9755c5f3c", entity.getPid())) {
			wrapper.andNew().in("c.eid", list).or().eq("c.entry", userid);
		}
		page.setRecords(baseMapper.selectVoPage(page, wrapper));
		return page;
	}

	@Override
	public List<Customer> selectLastFollow(Wrapper wrapper) {
		return customerMapper.selectLastFollow(wrapper);
	}

	@Override
	public boolean deleteIds(List<? extends Serializable> idList) {
		return customerMapper.batchDelete(idList) > 0 ? true : false;
	}

	@Override
	public boolean batchUpdateRecovery(List<? extends Serializable> idList) {
		return customerMapper.batchUpdateRecovery(idList) > 0 ? true : false;
	}

	@Override
	public boolean batchUpdateAssignment(String[] cid, String[] lv, String[] eid) throws Exception {
		// 去除前端重复参数
		Set<String> set = new HashSet<String>();
		set.addAll(Arrays.asList(cid));

		List<String> list = new ArrayList<String>();
		list.addAll(set);

		List<List<String>> list2 = new ArrayList<List<String>>();

		// 计算分配率的分配人数
		for (int i = 0; i < lv.length; i++) {
			List<String> list3 = new ArrayList<String>();
			if (!CommonUtil.isBlank(list)) {
				BigDecimal result = new BigDecimal(set.size() + "").multiply(new BigDecimal(lv[i]))
						.divide(new BigDecimal("100"));
				if (i == lv.length - 1) {// 剩下的客户id
					for (String object : list) {
						list3.add(object);
					}
				} else {
					for (int j = 0; j < result.setScale(0, BigDecimal.ROUND_HALF_UP).longValue(); j++) {
						list3.add(list.get(j));
					}
					list.removeAll(list3);
				}
			}
			list2.add(list3);
		}

		for (int i = 0; i < list2.size(); i++) {
			List<String> list3 = list2.get(i);
			for (int j = 0; j < list3.size(); j++) {
				String cid2 = list3.get(j);
				Customer customer = baseMapper.selectById(cid2);
				// 跟进人id
				customer.setEid(eid[i]);
				// 预约面试时间
				customer.setIvtm(null);
				// 是否上门:1-是、2-否
				customer.setIsvisit(null);
				// 分配跟进人
				if (baseMapper.updateAllColumnById(customer) > 0) {
					// 添加跟进记录
					Customerfw entity = new Customerfw();
					// 客户id
					entity.setCid(customer.getId());
					// 跟进人id
					entity.setEid(customer.getEid());
					// 时间
					entity.setTime(CommonUtil.getDate());
					// 类型：1-主动跟进、2-客户咨询、3-分配跟进人
					entity.setType(new BigDecimal(3));
					customerfwMapper.insert(entity);
				} else {
					throw new Exception("分配跟进人失败");
				}

			}
		}
		return true;
	}

	@Override
	public List batchImportExcel(List customers, String rstype, String entry) throws Exception {

		List exist = new ArrayList();

		if ((CommonUtil.isEquals("1", rstype) || CommonUtil.isEquals("2", rstype))) {
			// 去除文档的重复数据
			Map<String, CustomerResumeVo> map = new HashMap();
			for (Object object : customers) {
				if (object instanceof CustomerResumeVo) {
					CustomerResumeVo customer = (CustomerResumeVo) object;
					map.put(customer.getPhone(), customer);
				}
			}
			List<CustomerResumeVo> list = new ArrayList<CustomerResumeVo>();
			list.addAll(map.values());

			List<Customer> noExist = new ArrayList();
			// 已存在数据
			Wrapper wrapper2 = Condition.create();
			wrapper2.setSqlSelect("phone");
			List<BigDecimal> phones = customerMapper.selectObjs(wrapper2);
			List<String> phoneStrs = new ArrayList();
			for (BigDecimal bigDecimal : phones) {
				if (!CommonUtil.isBlank(bigDecimal)) {
					phoneStrs.add(bigDecimal.toString());
				}
			}
			for (CustomerResumeVo customer : list) {
				if (!CommonUtil.isBlank(customer.getPhone())) {
					if (phoneStrs.contains(customer.getPhone())) {
						// 已经存在的手机号码
						exist.add(customer.getPhone());
					} else {
						// 不存在的手机号码
						Customer customer3 = new Customer();
						// 学校id
						customer3.setSid(customer.getSid());
						// 专业
						customer3.setDid(customer.getDid());
						// 跟进人
						customer3.setEid(entry);
						// 名称
						customer3.setName(customer.getName());
						if (!CommonUtil.isBlank(customer.getPhone())) {
							customer3.setPhone(new BigDecimal(customer.getPhone()));
						}
						if (!CommonUtil.isBlank(customer.getEctn())) {
							customer3.setEctn(new BigDecimal(customer.getEctn()));
						}
						// 录入人
						customer3.setEntry(entry);
						// 录入时间
						customer3.setEttm(CommonUtil.getDate());

						// 简历类型：1-51job、2-智联、3-自定义
						customer3.setRstype(new BigDecimal(rstype));
						customer3.setLabl(customer.getLabl());
						customer3.setPtap(customer.getPtap());

						if (CommonUtil.isEquals("1", rstype)) {
							// 51job
							// customer3.setAptm(customer.getAptm());
							// 1997-07
							if (!CommonUtil.isBlank(customer.getBirth())) {
								SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
								customer3.setBirth(dateFormat.parse(customer.getBirth()));
							}
						}
						if (CommonUtil.isEquals("2", rstype)) {
							// 智联
							if (!CommonUtil.isBlank(customer.getAptm())) {
								customer3.setAptm(CommonUtil.getDate(customer.getAptm(), "ISO"));
							}
							if (!CommonUtil.isBlank(customer.getBirth())) {
								// 1997/8
								SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
								customer3.setBirth(dateFormat.parse(customer.getBirth()));
							}
						}
						if (CommonUtil.isEquals("3", rstype)) {
							// 自定义
							// customer3.setAptm(customer.getAptm());
							// customer3.setBirth(customer.getBirth());
						}

						if (!CommonUtil.isBlank(customer.getSex())) {
							customer3.setSex(new BigDecimal(customer.getSex()));
						}

						customer3.setResidence(customer.getResidence());
						customer3.setResident(customer.getResident());
						customer3.setWkyear(customer.getWkyear());
						customer3.setEmail(customer.getEmail());
						customer3.setAddr(customer.getAddr());
						customer3.setBfcompany(customer.getBfcompany());
						customer3.setBfposition(customer.getBfposition());
						customer3.setSalary(customer.getSalary());

						customer3.setExperience(customer.getExperience());
						customer3.setSelf(customer.getSelf());
						noExist.add(customer3);
					}
				}
			}
			if (CommonUtil.isBlank(noExist)) {
				return exist;
			}
			// 学校名称不存在start
			// excel数据
			// 学校名称
			Wrapper wrapper1 = Condition.create();// .ne("del", 2);
			List<School> schools = schoolMapper.selectList(null);

			Map<String, School> schoolmap = new HashMap<String, School>();
			for (School school : schools) {
				schoolmap.put(school.getName(), school);
			}
			Set<String> set = new HashSet<String>();
			for (Customer customer : noExist) {
				if (!CommonUtil.isBlank(customer.getSid())) {
					School school = schoolmap.get(customer.getSid());
					if (CommonUtil.isBlank(school)) {
						set.add(customer.getSid());
					}
				}
			}
			List schoollist = new ArrayList();
			for (String sname : set) {
				// 学校名称不存在
				School school2 = new School();
				school2.setName(sname);
				// 合作级别：1-深度合作、2-一般合作、3-意向合作、4-没合作
				school2.setLevel(new BigDecimal(4));
				schoollist.add(school2);
			}
			if (!CommonUtil.isBlank(schoollist)) {
				// 新增系统没有的学校信息
				schoolMapper.batchInsert(schoollist);
			}
			// 学校名称不存在end

			// 再次查询学校信息匹配客户
			List<School> schools2 = schoolMapper.selectList(null);
			schoolmap = new HashMap();
			for (School school : schools2) {
				schoolmap.put(school.getName(), school);
			}

			for (Customer customer : noExist) {
				if (!CommonUtil.isBlank(customer.getSid())) {
					School school = schoolmap.get(customer.getSid());
					customer.setSid(school.getId());
				}
			}

			insertBatch(noExist);
		} else if (CommonUtil.isEquals("3", rstype)) {

			// 去除文档的重复数据
			Map<String, CustomerVo> map = new HashMap<String, CustomerVo>();
			for (Object object : customers) {
				if (object instanceof CustomerVo) {
					CustomerVo customer = (CustomerVo) object;
					map.put(customer.getPhone().toString(), customer);
				}
			}
			List<CustomerVo> list = new ArrayList<CustomerVo>();
			list.addAll(map.values());

			List<Customer> noExist = new ArrayList();
			// 已存在数据
			Wrapper wrapper2 = Condition.create();
			wrapper2.setSqlSelect("phone");
			List<BigDecimal> phones = customerMapper.selectObjs(wrapper2);
			List<String> phoneStrs = new ArrayList();
			for (BigDecimal bigDecimal : phones) {
				if (!CommonUtil.isBlank(bigDecimal)) {
					phoneStrs.add(bigDecimal.toString());
				}
			}

			for (CustomerVo customer : list) {
				if (!CommonUtil.isBlank(customer.getPhone())) {
					if (phoneStrs.contains(customer.getPhone().toString())) {
						// 已经存在的手机号码
						exist.add(customer.getPhone());
					} else {
						// 不存在的手机号码
						Customer customer3 = new Customer();

						customer3.setCid(customer.getCid());
						customer3.setQq(customer.getQq());
						customer3.setWechat(customer.getWechat());
						customer3.setEctn(customer.getEctn());
						customer3.setPeriod(customer.getPeriod());
						customer3.setOttn(customer.getOttn());
						customer3.setElmt(customer.getElmt());
						customer3.setIntt(customer.getIntt());
						customer3.setEntry(customer.getEntry());
						customer3.setEttm(customer.getEttm());
						customer3.setIvtm(customer.getIvtm());
						customer3.setIsvisit(customer.getIsvisit());
						customer3.setRstype(customer.getRstype());
						customer3.setLabl(customer.getLabl());
						customer3.setPtap(customer.getPtap());
						customer3.setAptm(customer.getAptm());
						customer3.setSex(customer.getSex());
						customer3.setBirth(customer.getBirth());

						// 学校id
						customer3.setSid(customer.getSid());
						// 专业
						customer3.setDid(customer.getDid());
						// 跟进人
						customer3.setEid(entry);
						// 名称
						customer3.setName(customer.getName());
						if (!CommonUtil.isBlank(customer.getPhone())) {
							customer3.setPhone(customer.getPhone());
						}
						if (!CommonUtil.isBlank(customer.getEctn())) {
							customer3.setEctn(customer.getEctn());
						}
						// 录入人
						customer3.setEntry(entry);
						// 录入时间
						customer3.setEttm(CommonUtil.getDate());

						// 简历类型：1-51job、2-智联、3-自定义
						customer3.setRstype(new BigDecimal(rstype));
						customer3.setLabl(customer.getLabl());
						customer3.setPtap(customer.getPtap());

						if (!CommonUtil.isBlank(customer.getBirth())) {
							customer3.setBirth(customer.getBirth());
						}
						if (!CommonUtil.isBlank(customer.getAptm())) {
							customer3.setAptm(customer.getAptm());
						}

						if (!CommonUtil.isBlank(customer.getSex())) {
							customer3.setSex(customer.getSex());
						}

						customer3.setResidence(customer.getResidence());
						customer3.setResident(customer.getResident());
						customer3.setWkyear(customer.getWkyear());
						customer3.setEmail(customer.getEmail());
						customer3.setAddr(customer.getAddr());
						customer3.setBfcompany(customer.getBfcompany());
						customer3.setBfposition(customer.getBfposition());
						customer3.setSalary(customer.getSalary());

						noExist.add(customer3);
					}
				}
			}
			if (CommonUtil.isBlank(noExist)) {
				return exist;
			}

			// 学校名称不存在start
			// excel数据
			// 学校名称
			Wrapper wrapper1 = Condition.create();// .ne("del", 2);
			List<School> schools = schoolMapper.selectList(null);

			Map<String, School> schoolmap = new HashMap<String, School>();
			for (School school : schools) {
				schoolmap.put(school.getName(), school);
			}
			Set<String> set = new HashSet<String>();
			for (Customer customer : noExist) {
				if (!CommonUtil.isBlank(customer.getSid())) {
					School school = schoolmap.get(customer.getSid());
					if (CommonUtil.isBlank(school)) {
						set.add(customer.getSid());
					}
				}
			}
			List schoollist = new ArrayList();
			for (String sname : set) {
				// 学校名称不存在
				School school2 = new School();
				school2.setName(sname);
				// 合作级别：1-深度合作、2-一般合作、3-意向合作、4-没合作
				school2.setLevel(new BigDecimal(4));
				schoollist.add(school2);
			}

			// 新增系统没有的学校信息
			schoolMapper.batchInsert(schoollist);
			// 学校名称不存在end

			// 再次查询学校信息匹配客户
			List<School> schools2 = schoolMapper.selectList(null);
			schoolmap = new HashMap();
			for (School school : schools2) {
				schoolmap.put(school.getName(), school);
			}
			for (Customer customer : noExist) {
				if (!CommonUtil.isBlank(customer.getSid())) {
					School school = schoolmap.get(customer.getSid());
					customer.setSid(school.getId());
				}
			}
			insertBatch(noExist);
		}
		return exist;
	}

}
